package com.mxpio.erp.equipment.controller;

import com.mxpio.erp.common.equipment.entity.EquipmentStockRkApply;
import com.mxpio.erp.common.equipment.entity.EquipmentStockRkApplyItem;
import com.mxpio.erp.common.equipment.entity.EquipmentStockRkHistory;
import com.mxpio.erp.common.equipment.service.EquipmentStockRkApplyItemService;
import com.mxpio.erp.common.equipment.service.EquipmentStockRkApplyService;
import com.mxpio.erp.common.equipment.service.EquipmentStockRkHistoryService;
import com.mxpio.erp.common.equipment.vo.VEquipmentStockRkPosting;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
* @Description: 备品入库
* @Author: jeecg-boot
* @Date:   2021-10-07
* @Version: V1.0
*/
@Tag(name = "EquipmentStockRkApplyController", description = "备品入库")
@RestController
@RequestMapping("/rk/tpmStockRkApply")
@Slf4j
public class EquipmentStockRkApplyController{

   @Autowired
   private EquipmentStockRkApplyService tpmStockRkApplyService;

   @Autowired
   private EquipmentStockRkApplyItemService tpmStockRkApplyItemService;
   @Autowired
   private EquipmentStockRkHistoryService tpmStockRkHistoryService;

   /*---------------------------------主表处理-begin-------------------------------------*/

   /**
    * 分页列表查询
    * @param criteria
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @Operation(summary = "备品入库-分页列表查询", description = "备品入库-分页列表查询", method = "GET")
   @GetMapping(value = "/page")
   public Result<?> queryPageList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                  Criteria criteria,
                                  HttpServletRequest req) {
       Pageable page = PageRequest.of(pageNo-1, pageSize);
       Page<EquipmentStockRkApply> pageList = tpmStockRkApplyService.listPage(EquipmentStockRkApply.class,page, criteria);
       return Result.OK(pageList);
   }


   /**
    *   添加
    * @param tpmStockRkApply
    * @return
    */
   @Operation(summary = "备品入库-添加", description = "备品入库-添加", method = "POST")
   @PostMapping(value = "/add")
   public Result<?> add(@RequestBody EquipmentStockRkApply tpmStockRkApply) {
       tpmStockRkApply.setIsDel(0);
       tpmStockRkApply.setVersion(0);
       tpmStockRkApply.setStatus(0);
       tpmStockRkApplyService.save(tpmStockRkApply);
       return Result.OK("添加成功！");
   }

   /**
    *  编辑
    * @param tpmStockRkApply
    * @return
    */
   @Operation(summary = "备品入库-编辑", description = "备品入库-编辑", method = "PUT")
   @PutMapping(value = "/edit")
   public Result<?> edit(@RequestBody EquipmentStockRkApply tpmStockRkApply) {
       tpmStockRkApply.setVersion(tpmStockRkApply.getVersion()+1);
       tpmStockRkApplyService.update(tpmStockRkApply);
       return Result.OK("编辑成功!");
   }

    /**
     *  提交
     * @param tpmStockRkApply
     * @return
     */
    @Operation(summary = "备品入库-提交", description = "备品入库-提交", method = "PUT")
    @PutMapping(value = "/submit")
    public Result<?> submit(@RequestBody EquipmentStockRkApply tpmStockRkApply) {
        List<EquipmentStockRkApplyItem> itemList = tpmStockRkApplyItemService.selectByMainId(tpmStockRkApply.getId());
        if (itemList.isEmpty()){
            return Result.error("该入库单没有添加详情信息，不允许提交！");
        }
        return Result.OK(tpmStockRkApplyService.submit(tpmStockRkApply,itemList));
    }


   /**
    * 通过id删除
    * @param id
    * @return
    */
   @Operation(summary = "备品入库-通过id删除", description = "备品入库-通过id删除", method = "DELETE")
   @DeleteMapping(value = "/delete/{id}")
   public Result<?> delete(@PathVariable(name = "id", required = true) String id) {
       tpmStockRkApplyService.delMain(id);
       return Result.OK("删除成功!");
   }

   /**
    * 批量删除
    * @param ids
    * @return
    */
   @Operation(summary = "备品入库-批量删除", description = "备品入库-批量删除", method = "DELETE")
   @DeleteMapping(value = "/deleteBatch/{ids}")
   public Result<?> deleteBatch(@PathVariable(name="ids",required=true) String ids) {
       this.tpmStockRkApplyService.delBatchMain(Arrays.asList(ids.split(",")));
       return Result.OK("批量删除成功!");
   }

   /**
    * 导出
    * @return
    *//*
   @RequestMapping(value = "/exportXls")
   public ModelAndView exportXls(HttpServletRequest request, EquipmentStockRkApply tpmStockRkApply) {
       return super.exportXls(request, tpmStockRkApply, EquipmentStockRkApply.class, "备品入库");
   }

   *//**
    * 导入
    * @return
    *//*
   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       return super.importExcel(request, response, EquipmentStockRkApply.class);
   }*/
   /*---------------------------------主表处理-end-------------------------------------*/


   /*--------------------------------子表处理-入库单明细-begin----------------------------------------------*/
   /**
    * 通过主表ID查询
    * @return
    */
   @Operation(summary = "入库单明细-通过主表ID查询", description = "入库单明细-通过主表ID查询", method = "GET")
   @GetMapping(value = "/listEquipmentStockRkApplyItemByMainId")
   public Result<?> listEquipmentStockRkApplyItemByMainId(EquipmentStockRkApplyItem tpmStockRkApplyItem,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          Criteria criteria,
                                                   HttpServletRequest req) {
       Pageable page = PageRequest.of(pageNo-1, pageSize);
       //Page<EquipmentStockRkApplyItem> pageList = tpmStockRkApplyItemService.queryByMainId(page, tpmStockRkApplyItem.getApplyId());
       Page<EquipmentStockRkApplyItem> pageList = tpmStockRkApplyItemService.listPage(EquipmentStockRkApplyItem.class, page, criteria);
       return Result.OK(pageList);
   }

   /**
    * 添加
    * @param tpmStockRkApplyItem
    * @return
    */
   @Operation(summary = "入库单明细-添加", description = "入库单明细-添加", method = "POST")
   @PostMapping(value = "/addEquipmentStockRkApplyItem")
   public Result<?> addEquipmentStockRkApplyItem(@RequestBody EquipmentStockRkApplyItem tpmStockRkApplyItem) {
           tpmStockRkApplyItemService.saveItem(tpmStockRkApplyItem);
       return Result.OK("添加成功！");
   }

   /**
    * 编辑
    * @param tpmStockRkApplyItem
    * @return
    */
   @Operation(summary = "入库单明细-编辑", description = "入库单明细-编辑", method = "PUT")
   @PutMapping(value = "/editEquipmentStockRkApplyItem")
   public Result<?> editEquipmentStockRkApplyItem(@RequestBody EquipmentStockRkApplyItem tpmStockRkApplyItem) {
       tpmStockRkApplyItemService.updateItemById(tpmStockRkApplyItem);
       return Result.OK("编辑成功!");
   }

   /**
    * 通过id删除
    * @param id
    * @return
    */
   @Operation(summary = "入库单明细-通过id删除", description = "入库单明细-通过id删除", method = "DELETE")
   @DeleteMapping(value = "/deleteEquipmentStockRkApplyItem/{id}")
   public Result<?> deleteEquipmentStockRkApplyItem(@PathVariable(name="id",required=true) String id) {
       tpmStockRkApplyItemService.remove(EquipmentStockRkApplyItem.class,id);
       return Result.OK("删除成功!");
   }

   /**
    * 批量删除
    * @param ids
    * @return
    */
   @Operation(summary = "入库单明细-批量删除", description = "入库单明细-批量删除", method = "DELETE")
   @DeleteMapping(value = "/deleteBatchEquipmentStockRkApplyItem/{ids}")
   public Result<?> deleteBatchEquipmentStockRkApplyItem(@PathVariable(name="ids",required=true) String ids) {
       Criteria c = Criteria.create().addCriterion("id", Operator.IN, Arrays.asList(ids.split(",")));
       tpmStockRkApplyItemService.removeBatch(EquipmentStockRkApplyItem.class,c);
       return Result.OK("批量删除成功!");
   }

   /**
    * 导出
    * @return
    *//*
   @RequestMapping(value = "/exportEquipmentStockRkApplyItem")
   public ModelAndView exportEquipmentStockRkApplyItem(HttpServletRequest request, EquipmentStockRkApplyItem tpmStockRkApplyItem) {
        // Step.1 组装查询条件
        QueryWrapper<EquipmentStockRkApplyItem> queryWrapper = QueryGenerator.initQueryWrapper(tpmStockRkApplyItem, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<EquipmentStockRkApplyItem> pageList = tpmStockRkApplyItemService.list(queryWrapper);
        List<EquipmentStockRkApplyItem> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "入库单明细"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, EquipmentStockRkApplyItem.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("入库单明细报表", "导出人:" + sysUser.getRealname(), "入库单明细"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
   }

   *//**
    * 导入
    * @return
    *//*
   @RequestMapping(value = "/importEquipmentStockRkApplyItem/{mainId}")
   public Result<?> importEquipmentStockRkApplyItem(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<EquipmentStockRkApplyItem> list = ExcelImportUtil.importExcel(file.getInputStream(), EquipmentStockRkApplyItem.class, params);
                for (EquipmentStockRkApplyItem temp : list) {
                   temp.setApplyId(mainId);
                }
                long start = System.currentTimeMillis();
                tpmStockRkApplyItemService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.OK("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
   }*/

   /*--------------------------------子表处理-入库单明细-end----------------------------------------------*/

    /*--------------------------------入库过账处理-start----------------------------------------------*/

    /**
     * 通过主表ID查询入库过账历史
     * @return
     */
    @Operation(summary = "入库过账历史-通过主表ID查询", description = "入库过账历史-通过主表ID查询", method = "GET")
    @GetMapping(value = "/applyHistory")
    public Result<?> queryRkApplyHistoryByMainId(Criteria criteria, @RequestParam(name="applyId", defaultValue="") String applyId,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        //Page<EquipmentStockRkHistory> pageList = tpmStockRkHistoryService.queryRkApplyHistoryByMainId(page, applyId);
        Page<EquipmentStockRkHistory> pageList = tpmStockRkHistoryService.listPage(EquipmentStockRkHistory.class, page, criteria);
        return Result.OK(pageList);
    }
    /**
     * 通过主表ID查询入库过账历史详情
     * @return
     */
    @Operation(summary = "入库过账历史详情-通过主表ID查询", description = "入库过账历史详情-通过主表ID查询", method = "GET")
    @GetMapping(value = "/applyHistoryDetail")
    public Result<?> queryRkApplyHistoryDetailByMainId(Criteria criteria,
                                                EquipmentStockRkHistory tpmStockRkHistory,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        //Page<VEquipmentStockRkHistoryDetail> pageList = tpmStockRkHistoryService.queryRkApplyHistoryDetailByMainId(page, tpmStockRkHistory);
        //避免自定义查询，冗余存储了tpm_material、tpm_stock_rk_apply中的所需字段
        Page<EquipmentStockRkHistory> pageList = tpmStockRkHistoryService.listPage(EquipmentStockRkHistory.class, page, criteria);
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     * @param tpmStockRkApply
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @Operation(summary = "备品入库过账-分页列表查询", description = "备品入库过账-分页列表查询", method = "GET")
    @GetMapping(value = "/listPosting")
    public Result<?> queryPageListPosting(EquipmentStockRkApply tpmStockRkApply,
                                          Criteria criteria,
                                          @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                          @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                          HttpServletRequest req) {
        criteria.addCriterion("status", Operator.EQ, 1);
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<EquipmentStockRkApply> pageList = tpmStockRkApplyService.listPage(EquipmentStockRkApply.class,page, criteria);
        return Result.OK(pageList);
    }

    /**
     * 通过主表ID查询
     * @return
     */
    @Operation(summary = "入库单待入账详情-通过主表ID查询", description = "入库单待入账详情-通过主表ID查询", method = "GET")
    @GetMapping(value = "/queryRkPostingItemByMainId")
    public Result<?> queryRkPostingItemByMainId(EquipmentStockRkApplyItem tpmStockRkApplyItem,
                                                Criteria criteria,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<EquipmentStockRkApplyItem> pageList = tpmStockRkApplyItemService.queryRkPostingByMainId(page, tpmStockRkApplyItem.getApplyId());
        return Result.OK(pageList);
    }

    /**
     * 入库过账
     * @param tpmStockRkPostingVo
     * @return
     */
    @Operation(summary = "入库过账", description = "入库过账", method = "POST")
    @PostMapping(value = "/rkPosting")
    public Result<?> rkPosting(@RequestBody VEquipmentStockRkPosting tpmStockRkPostingVo) {
        tpmStockRkApplyService.rkPosting(tpmStockRkPostingVo);
        return Result.OK("添加成功！");
    }
    /**
     * 拒绝入库
     * @param tpmStockRkPostingVo
     * @return
     */
    @Operation(summary = "拒绝入库", description = "拒绝入库", method = "POST")
    @PostMapping(value = "/rkReject")
    public Result<?> rkReject(@RequestBody VEquipmentStockRkPosting tpmStockRkPostingVo) {
        tpmStockRkApplyService.rkPosting(tpmStockRkPostingVo);
        return Result.OK("添加成功！");
    }


}
